import { useState, useEffect } from 'react'
import useSyncState from '@/utils/tongbu'
import { useNavigate } from 'react-router-dom'
import { GetAddress, DefaultAddress } from '@/api/address'
import style from './index.module.scss'
import { Toast, Button, Radio, Tag } from 'antd-mobile'
import { EditSOutline } from 'antd-mobile-icons'

import HeaderView from '@/components/Header/index'
import LoadingView from '@/components/Loading/index'

const Address = () => {
  const [flag, setFlag] = useState(true)
  const [loadingCode, setLoadingCode] = useState(1) 
  const [list, setList] = useSyncState([]) // 地址列表
  const [radioValue, setRadioValue] = useState<string | number>(0) // 默认选中地址的radio
  const navigate = useNavigate()   

  // 数据初始化
  const init = async () => {
    const res = await GetAddress().catch((err) => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setLoadingCode(2)
      if (err.status === 401) Toast.show({icon: 'fail', content: '请先登录呀', maskClickable: false, duration: 1000, afterClose: () => {
        navigate('/login', {state: {fromPath: '/address'}})
      }})
    })

    if(res?.status === 200) {
      setFlag(false)
      setList(res.data.data, (data: any) => {
        const item = data.find((item: any) => item.is_default === 1)
        item === undefined ? setRadioValue(0) : setRadioValue(item.id)
      })
    }
  }

  useEffect(() => {
    init()
  }, [])

 

  const radioClick = async (id: number) => {
    const res = await DefaultAddress(id).catch((err) => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') Toast.show({icon: 'fail', content: '网络出错', duration: 1000})
    })

    if(res?.status === 204) Toast.show({content: '默认地址更新成功', duration: 500, afterClose: () => init()})
  }


  // 地址列表
  const getList = () => {
    return list.map((item: {province: string, city: string, county: string, address: string, name: string, phone: number, id: number, is_default: number }) => {
      return(
        <div className={style.item} key={item.id}>
          <div className={style.itemLeft}>
            <div className={style.leftRadio}><Radio onClick={() => radioClick(item.id)} value={item.id}/></div>
            <div className={style.leftDesc}>
              <p>{item.name}---{item.phone} {item.is_default === 1 && <Tag round color='#2db7f5'>默认</Tag>}</p>
              <p className={style.city}>{item.province}---{item.city}---{item.county}</p>
              <p>{item.address}</p>
            </div>
          </div>
          <div className={style.itemRight}><EditSOutline onClick={() => navigate('/editAddress', {state: {type: 'edit', id: item.id}})} fontSize={18}/></div>
        </div>
      )
    })
  }

  return (
    <>
      {/* 头部信息 */}
      <HeaderView title='地址管理' backIcon={true} backPath='mine'></HeaderView>

      {/* 地址列表 */}
      <div className={style.content}>
        <Radio.Group value={radioValue} onChange={(val: string | number) => setRadioValue(val)}>
          {getList()}
        </Radio.Group>
      </div>

      <div className={style.btn}>
        <Button block color='primary' size='large' onClick={() => navigate('/editAddress', {state: {type: 'add'}})}>新增地址</Button>
      </div>
      {/* 加载中或者加载超时 */}
      {flag && <LoadingView loadingCode={loadingCode}></LoadingView>}
    </>
  )
}

export default Address